package art.client.activites;

import java.util.List;

import art.client.ClientFactory;
import art.client.ClientUtils;
import art.client.views.UserArtsView;
import art.shared.entities.ArtShared;
import art.shared.entities.GenreShared;
import art.shared.entities.LoginInfo;

import com.google.gwt.activity.shared.AbstractActivity;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.AcceptsOneWidget;

public class UserArtsActivity extends AbstractActivity {

	private ClientFactory clientFactory = null;
	private LoginInfo loginInfo = null;

	public UserArtsActivity(ClientFactory clientFactory, LoginInfo loginInfo) {
		this.clientFactory = clientFactory;
		this.loginInfo = loginInfo;
	}

	@Override
	public void start(AcceptsOneWidget containerWidget, EventBus eventBus) {
		initView(containerWidget);
	}

	private void initView(final AcceptsOneWidget containerWidget) {
		if (loginInfo == null) {
			ClientUtils.getUserService().getLoginInfo(
					new AsyncCallback<LoginInfo>() {

						@Override
						public void onSuccess(LoginInfo loginInfo) {
							executeInit(containerWidget);
						}

						@Override
						public void onFailure(Throwable arg0) {

						}
					});
		} else {
			executeInit(containerWidget);
		}
	}

	private void executeInit(final AcceptsOneWidget containerWidget) {

		ClientUtils.getArtService().getGenres(
				new AsyncCallback<List<GenreShared>>() {

					@Override
					public void onFailure(Throwable arg0) {
					}

					@Override
					public void onSuccess(List<GenreShared> genres) {
						UserArtsView artsView = clientFactory.getUserArtsView(
								loginInfo, genres);
						containerWidget.setWidget(artsView.asWidget());
						getArtsAndUpdateTable(artsView, loginInfo.getUser().getId());
					}
				});

	}

	private void getArtsAndUpdateTable(final UserArtsView artsView,
			final long userId) {
		final AsyncCallback<List<ArtShared>> acb = new AsyncCallback<List<ArtShared>>() {
			public void onFailure(Throwable error) {
			}

			public void onSuccess(List<ArtShared> result) {
				artsView.updateTable(result);
			}
		};
		ClientUtils.getArtService().getArtsOfUser(userId, acb);
	}

}
